package com.zkthink.ceres.order.service.impl;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.lang.Snowflake;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zkthink.base.R;
import com.zkthink.cache.repository.RedisRepositoryImpl;
import com.zkthink.ceres.order.constants.CommentConstant;
import com.zkthink.ceres.order.dao.SensitiveKeywordMapper;
import com.zkthink.ceres.order.dto.comment.AddSensitiveKeywordDTO;
import com.zkthink.ceres.order.dto.comment.FindKeywordListDTO;
import com.zkthink.ceres.order.dto.comment.SensitiveKeywordPageDTO;
import com.zkthink.ceres.order.dto.comment.UpdateKeywordSettingDTO;
import com.zkthink.ceres.order.entity.OrderProduct;
import com.zkthink.ceres.order.entity.SensitiveKeyword;
import com.zkthink.ceres.order.service.SensitiveKeywordService;
import com.zkthink.base.service.SuperServiceImpl;

import com.zkthink.ceres.product.dto.IdQueryDTO;
import com.zkthink.ceres.promotion.entity.Promotion;
import com.zkthink.database.mybatis.conditions.Wraps;
import com.zkthink.exception.code.ExceptionCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 业务实现类
 * 敏感词表
 * </p>
 *
 * @author JustArgo
 * @date 2020-07-12
 */
@Slf4j
@Service
public class SensitiveKeywordServiceImpl extends SuperServiceImpl<SensitiveKeywordMapper, SensitiveKeyword> implements SensitiveKeywordService {

    @Autowired
    private Snowflake snowflake;

    @Autowired
    private RedisRepositoryImpl redisRepository;

    @Override
    public R<Boolean> addSensitiveKeyword(AddSensitiveKeywordDTO addDTO) {
        String keyword = addDTO.getSensitiveKeyword();
        Integer action = addDTO.getAction();
        Integer enabled = addDTO.getEnabled();
        if (StringUtils.isBlank(keyword)) {
            return R.fail(ExceptionCode.ILLEGALA_ARGUMENT_EX.getCode(), "关键词不能为空");
        }
        Long id = null;
        SensitiveKeyword sensitiveKeyword = baseMapper.selectOne(Wraps.<SensitiveKeyword>lbQ().eq(SensitiveKeyword::getSensitiveKeyword, keyword));
        if (sensitiveKeyword != null) {
            if (sensitiveKeyword.getIsDelete() == 1) {
                sensitiveKeyword.setAction(action);
                sensitiveKeyword.setEnabled(enabled);
                sensitiveKeyword.setIsDelete(0);
                id = sensitiveKeyword.getId();
                baseMapper.updateById(sensitiveKeyword);
            } else {
                return R.fail(ExceptionCode.OPERATION_EX.getCode(), "该敏感词已存在,不能重复添加");
            }
        } else {
            SensitiveKeyword newKeyword = new SensitiveKeyword();
            newKeyword.setEnabled(enabled);
            newKeyword.setAction(action);
            newKeyword.setSensitiveKeyword(keyword);
            baseMapper.insert(newKeyword);
            id = newKeyword.getId();
        }

        redisRepository.getRedisTemplate().opsForZSet().add(CommentConstant.SENSITIVE_LIST,keyword,id);

        return R.success();
    }

    @Override
    public R<Boolean> deleteSensitiveKeyword(IdQueryDTO queryDTO) {
        SensitiveKeyword sensitiveKeyword = baseMapper.selectById(queryDTO.getId());
        baseMapper.logicDeleteByIds(new ArrayList<>(Arrays.asList(queryDTO.getId())));
        redisRepository.getRedisTemplate().opsForZSet().remove(CommentConstant.SENSITIVE_LIST,sensitiveKeyword.getSensitiveKeyword());
        return R.success();
    }

    @Override
    public R<SensitiveKeywordPageDTO> findSensitiveKeywordList(FindKeywordListDTO keywordListDTO) {
        if (keywordListDTO == null) {
            return R.fail(ExceptionCode.ILLEGALA_ARGUMENT_EX);
        }
        SensitiveKeywordPageDTO pageDTO = new SensitiveKeywordPageDTO();

        Page<SensitiveKeyword> sensitiveKeywordPage = new Page<>(keywordListDTO.getPageIndex(), keywordListDTO.getPageSize());
        IPage<SensitiveKeyword> page = baseMapper.selectPage(sensitiveKeywordPage,Wraps.<SensitiveKeyword>lbQ().eq(SensitiveKeyword::getIsDelete, false)
                .like(StringUtils.isNotBlank(keywordListDTO.getKeyword()), SensitiveKeyword::getSensitiveKeyword,
                        keywordListDTO.getKeyword()).orderByDesc(SensitiveKeyword::getCreateTime));

        pageDTO.setTotal(Integer.valueOf(page.getTotal()+""));
        pageDTO.setSensitiveKeywordList(page.getRecords());
        return R.success(pageDTO);
    }

    @Override
    public R<Boolean> updateSensitiveKeywordSetting(UpdateKeywordSettingDTO updateKeywordSettingDTO) {
        SensitiveKeyword sensitiveKeyword = new SensitiveKeyword();
        sensitiveKeyword.setEnabled(updateKeywordSettingDTO.getEnabled());
        sensitiveKeyword.setAction(updateKeywordSettingDTO.getAction());
        baseMapper.update(sensitiveKeyword,Wraps.<SensitiveKeyword>lbQ().eq(SensitiveKeyword::getIsDelete,false));

        redisRepository.set(CommentConstant.SENSITIVE_KEYWORD_SETTING,sensitiveKeyword);

        return R.success();
    }

    @Override
    public R<Boolean> updateSensitiveKeyword(SensitiveKeyword sensitiveKeyword) {

        SensitiveKeyword originSensitiveKeyword = baseMapper.selectById(sensitiveKeyword.getId());

        List<SensitiveKeyword> list = baseMapper.selectList(Wraps.<SensitiveKeyword>lbQ()
                .eq(SensitiveKeyword::getSensitiveKeyword,sensitiveKeyword.getSensitiveKeyword())
                .eq(SensitiveKeyword::getIsDelete,false));
        if(list.size()>0 && !list.stream().map(SensitiveKeyword::getId).collect(Collectors.toList()).contains(sensitiveKeyword.getId())){
            return R.fail(ExceptionCode.ILLEGALA_ARGUMENT_EX.getCode(),"已存在该敏感词");
        }

        //如果和原来的不相等，并且现在是启用状态，需要删除redis旧关键词缓存，并且新增新关键词缓存
        if(!originSensitiveKeyword.getSensitiveKeyword().equals(sensitiveKeyword.getSensitiveKeyword())
            && sensitiveKeyword.getEnabled()==1){
            redisRepository.getRedisTemplate().opsForZSet().remove(CommentConstant.SENSITIVE_LIST,originSensitiveKeyword.getSensitiveKeyword());
            redisRepository.getRedisTemplate().opsForZSet().add(CommentConstant.SENSITIVE_LIST,sensitiveKeyword.getSensitiveKeyword(),sensitiveKeyword.getId());
        }

        baseMapper.updateById(sensitiveKeyword);
        return R.success();
    }

    @Override
    public Integer initSensitiveKeyword(){
        List<SensitiveKeyword> sensitiveKeywordList = baseMapper.selectList(Wraps.<SensitiveKeyword>lbQ().eq(SensitiveKeyword::getIsDelete,false));
        if(sensitiveKeywordList!=null){
            SensitiveKeyword setting = new SensitiveKeyword();
            setting.setEnabled(sensitiveKeywordList.get(0).getEnabled());
            setting.setAction(sensitiveKeywordList.get(0).getAction());
            redisRepository.set(CommentConstant.SENSITIVE_KEYWORD_SETTING,setting);

            for(SensitiveKeyword sensitiveKeyword:sensitiveKeywordList){
                redisRepository.getRedisTemplate().opsForZSet().add(CommentConstant.SENSITIVE_LIST,sensitiveKeyword.getSensitiveKeyword(),sensitiveKeyword.getId());
            }
        }
        return sensitiveKeywordList.size();
    }
}
